package com.example.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.example.model.logBo.DataDetail;
import com.example.model.logBo.TenantDto;
import com.example.model.logBo.TenantVo;
import com.example.service.TenantService;
import com.example.utils.ContractAddressManager;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.transaction.manager.TransactionProcessorFactory;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@NoArgsConstructor
@Data
public class TenantServiceImpl implements TenantService {
    public static final String LogsTracetoSourceABI = com.example.utils.IOUtil.readResourceAsString("abi/LogsTracetoSource.abi");
    private String LogsTracetoSourceAddress = ContractAddressManager.getAddressFromContractNote("LogsTracetoSource");




    @Autowired
    private Client client;


    AssembleTransactionProcessor txProcessor;

    String clientPri;

    @PostConstruct
    public void init() throws Exception {
        this.txProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(this.client, this.client.getCryptoSuite().getCryptoKeyPair());
    }


    /**
     *
     * @param tenantDto 前端上传的参数
     * @throws Exception
     */
    @Override
    public void upload(TenantDto tenantDto) throws Exception {
        //智能合约函数对应的实体类
        List<Object> args = new ArrayList<>();
        //添加参数
        Collections.addAll(args, tenantDto.getTenantId(), tenantDto.getSysId(), tenantDto.getDataId());
        Collections.addAll(args, tenantDto.getDataName(), tenantDto.getDataType());
        DataDetail detail = tenantDto.getDataDetail();
        Collections.addAll(args, detail.getOperatorName(), detail.getOperatorTime());
        Collections.addAll(args, detail.getOperatorAction(), detail.getModuleName(), detail.getContent());

        //形成交易区块，完成上链
        this.txProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(this.client, this.client.getCryptoSuite().getCryptoKeyPair());
        TransactionResponse addRecord = this.txProcessor.sendTransactionAndGetResponse(this.LogsTracetoSourceAddress, LogsTracetoSourceABI, "addTenantRecord", args);
//        System.out.println("uploadAddRecord:"+JSONObject.toJSONString(addRecord));
    }

    /**
     * 到区块链根据租户ID查询历史日志
     * @param tenantId 租户ID
     * @return
     * @throws Exception
     */
    @Override
    public List<TenantVo> getByTenantId(String tenantId) throws Exception {

        List<Object> args = new ArrayList<>();

        Collections.addAll(args, tenantId);
        System.out.println("tenantId:"+tenantId);
        this.txProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(this.client, this.client.getCryptoSuite().getCryptoKeyPair());
        TransactionResponse addRecord = this.txProcessor.sendTransactionAndGetResponse(this.LogsTracetoSourceAddress, LogsTracetoSourceABI, "tenantIdtoProduct", args);
//        System.out.println("addRecord:"+ JSONObject.toJSONString(addRecord));
        //接收智能合约返回的内容
        List<List<Object>> data = (List<List<Object>>) addRecord.getReturnObject().get(0);
        List<TenantVo> tenantVos = new ArrayList<>();
        //遍历智能合约返回的内容，然后封装成对应vo
        for (List<Object> d : data) {
            TenantVo tenantVo = new TenantVo();
            tenantVo.setDataId((String) d.get(0));
            tenantVo.setDataName((String) d.get(1));
            tenantVo.setDataType((String) d.get(2));
            tenantVo.setSysId((String) d.get(3));
            tenantVos.add(tenantVo);
        }

        return tenantVos;
    }

    /**
     * 到区块链上根据系统ID查询日志详细信息
     * @param sysId
     * @return
     * @throws Exception
     */
    @Override
    public List<DataDetail> getDetailBySysId(String sysId) throws Exception {
        List<Object> args = new ArrayList<>();
        //添加向智能合约上传的参数
        Collections.addAll(args, sysId);

        this.txProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(this.client, this.client.getCryptoSuite().getCryptoKeyPair());
        TransactionResponse addRecord = this.txProcessor.sendTransactionAndGetResponse(this.LogsTracetoSourceAddress, LogsTracetoSourceABI, "sysIdtoDetail", args);
        //接收智能合约返回的内容
        //System.out.println("hhh" + addRecord.getReturnObject().get(0));
        List<List<Object>> data = (List<List<Object>>) addRecord.getReturnObject().get(0);
        List<DataDetail> detailList = new ArrayList<>();
        //遍历智能合约返回的内容，然后封装成对应vo
        for (List<Object> d : data) {
            DataDetail dataDetail = new DataDetail();
            dataDetail.setOperatorName((String) d.get(0));
            dataDetail.setOperatorTime((String) d.get(1));
            dataDetail.setOperatorAction((String) d.get(2));
            dataDetail.setModuleName((String) d.get(3));
            dataDetail.setContent((String) d.get(4));
            detailList.add(dataDetail);
        }
        //返回查询信息
        return detailList;
    }
}
